import cv2
import matplotlib.pyplot as plt
#
#
# #读取图片
# img1 = cv2.imread('eiffel_2.jpg')
# gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
#
# #获取关键点和描述符
# sift = cv2.xfeatures2d.SIFT_create()
# keypoints_1, descriptors_1 = sift.detectAndCompute(img1,None)
# kp = sift.detect(gray1,None)
#
# #可视化关键点
# img_1 = cv2.drawKeypoints(gray1,keypoints_1,img1,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# xlen=25
# plt.rcParams["figure.figsize"] = (xlen,xlen*(img_1.shape[1])/(img_1.shape[0]))
# plt.imshow(img_1)
# plt.axis('off')
#
# # 读取图片
# img1 = cv2.imread('eiffel_2.jpg')
# img2 = cv2.imread('eiffel_1.jpg')
# img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
#
# figure, ax = plt.subplots(1, 2, figsize=(16, 8))
#
# ax[0].imshow(img1, cmap='gray')
# ax[0].axis('off')
# ax[1].imshow(img2, cmap='gray')
# ax[1].axis('off')
#
#
# # 读取图片
# img1 = cv2.imread('eiffel_2.jpg')
# img2 = cv2.imread('eiffel_1.jpg')
# img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# #sift
# sift = cv2.xfeatures2d.SIFT_create()
# #获取关键点和描述符
# keypoints_1, descriptors_1 = sift.detectAndCompute(img1,None)
# keypoints_2, descriptors_2 = sift.detectAndCompute(img2,None)
# len(keypoints_1), len(keypoints_2)

#读取图片
img1 = cv2.imread('Eiffel_1.jpg')
img2 = cv2.imread('Eiffel_2.jpg')
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
#sift
sift = cv2.SIFT_create()
keypoints_1, descriptors_1 = sift.detectAndCompute(img1,None)
keypoints_2, descriptors_2 = sift.detectAndCompute(img2,None)
#使用BFmatcher（蛮力匹配）模块中的函数match() 特征匹配
bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True)
matches = bf.match(descriptors_1,descriptors_2)
matches = sorted(matches, key = lambda x:x.distance)
#把两个图像中匹配的特征之间画线
img3 = cv2.drawMatches(img1, keypoints_1, img2, keypoints_2, matches[:50], img2, flags=2)
plt.imshow(img3)
plt.axis('off')
plt.show()